package com.ahdy.tool;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
@Data
public class AliOSSUtils {
    @Value("${aliyun.oss.endpoint:https://oss-cn-hangzhou.aliyuncs.com}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId:LTAI5tFE1n5GyYFoQ64fMg4f}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret:VqmH6FmNiKbj4zLVVe1NJDEsZTEuAV}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName:old-people-docter}")
    private String bucketName;

    @Value("${aliyun.oss.dir:images/}")
    private String dir;

    /**
     * 上传文件到阿里云OSS
     * 
     * @param file 要上传的文件
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    public String upload(MultipartFile file) throws IOException {
        return upload(file, dir);
    }

    /**
     * 上传文件到阿里云OSS指定目录
     * 
     * @param file      要上传的文件
     * @param directory 存储目录
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    public String upload(MultipartFile file, String directory) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 获取文件输入流
        InputStream inputStream = file.getInputStream();

        try {
            // 生成安全的文件名
            String fileName = generateSafeFileName(file, directory);

            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            try {
                // 创建PutObjectRequest对象
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);

                // 上传文件
                ossClient.putObject(putObjectRequest);

                // 构建访问路径
                String url = "https://" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
                return url;
            } finally {
                // 关闭OSSClient
                ossClient.shutdown();
            }
        } finally {
            // 关闭输入流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // 忽略关闭异常
                }
            }
        }
    }

    /**
     * 生成安全的文件名，处理特殊字符和路径问题
     * 
     * @param file      文件
     * @param directory 目录
     * @return 安全的文件名
     */
    private String generateSafeFileName(MultipartFile file, String directory) {
        // 确保目录格式正确
        String safeDirectory = directory;
        if (!safeDirectory.endsWith("/")) {
            safeDirectory += "/";
        }

        // 取得文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成时间戳和UUID组合的文件名
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);

        // 构建完整文件名（目录+时间戳+uuid+后缀）
        return safeDirectory + timeStr + "-" + uuid + suffix;
    }

    /**
     * 删除OSS中的文件
     * 
     * @param objectName 文件名，包含路径
     * @return 是否删除成功
     */
    public boolean deleteFile(String objectName) {
        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 从URL中提取objectName
            if (objectName.startsWith("https://")) {
                String domain = "https://" + bucketName + "." + endpoint.split("//")[1] + "/";
                objectName = objectName.substring(domain.length());
            }

            // 删除文件
            ossClient.deleteObject(bucketName, objectName);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
